﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnitOfWorkDemo.Infrastructure;
using UnitOfWorkDemo.Model;

namespace UnitOfWorkDemo.Repository
{
    public class AccountRepository : IAccountRepository, IUnitOfWorkRepository
    {
        private readonly IUnitOfWork _unitOfWork;

        public AccountRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
            AccountList = new Hashtable();
        }

        public Hashtable AccountList { get; set; }

        #region IAccountRepository Members

        public void Save(Account account)
        {
            _unitOfWork.RegisterAmended(account, this);
        }

        public void Add(Account account)
        {
            _unitOfWork.RegisterNew(account, this);
        }

        public void Remove(Account account)
        {
            _unitOfWork.RegisterRemoved(account, this);
        }

        #endregion 

        #region IUnitOfWorkRepository Members

        public void PersistUpdateOf(IAggregateRoot entity)
        {
            // ADO.net code to update the entity...
            // 这里为了演示，只它持久化到内存中
            if (AccountList.ContainsKey(entity.Id))
            {
                AccountList[entity.Id] = entity;
            }
        }

        public void PersistCreationOf(IAggregateRoot entity)
        {
            // ADO.net code to Add the entity...
            // 这里为了演示，只它持久化到内存中
            AccountList.Add(entity.Id, entity);
        }

        public void PersistDeletionOf(IAggregateRoot entity)
        {
            // ADO.net code to delete the entity...
            // 这里为了演示，只它持久化到内存中
            if (AccountList.ContainsKey(entity.Id))
            {
                AccountList.Remove(entity.Id);
            }
        }
        #endregion 
    }
}